package boot.spring.controller;

import javax.servlet.http.HttpSession;

import boot.spring.entity.SocketUserEntity;
import boot.spring.service.SocketUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import boot.spring.po.User;


/**
 * @author pan.shun
 * @description 身份验证
 * @since 2022/6/15 14:18
 **/
@Controller
public class Login {
    @Autowired
    private SocketUserService socketUserService;

    @RequestMapping("/loginvalidate")
    public String loginvalidate(@RequestParam("username") String username, @RequestParam("password") String pwd, HttpSession httpSession) {
        if (username == null) {
            return "login";
        }
        boolean checkFlag = socketUserService.doCheckUser(username, pwd);
        if (checkFlag) {
            String uid = socketUserService.getUidByName(username, pwd);
            httpSession.setAttribute("uid", uid);
            return "chatroom";
        } else {
            return "fail";
        }
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession httpSession) {
        return "login";
    }

    @RequestMapping(value = "/currentuser", method = RequestMethod.GET)
    @ResponseBody
    public User currentuser(HttpSession httpSession) {
        String uid = (String) httpSession.getAttribute("uid");
        SocketUserEntity user = socketUserService.getById(uid);
        return new User(uid, user.getUserName());
    }
}
